package kz.edu.sdu.itech.qms;

import kz.edu.sdu.itech.qms.util.Logger;

public class Queue {
   public static final String WAITING = "waiting";
   public static final String SERVING = "serving";

   int yk = 0;
   int wk = 0;
   int n = 0;
   long time_to_serve = 0;
   Client[] q = new Client[QMSProps.QUEUE_SIZE];

   String queueState = Queue.WAITING;
   Logger log;
   int did;

   public Queue(int id) {
      this.did = id;
      log = new Logger(String.format("%s-%d", Queue.class.getName(), id));
   }

   public int getDid() {
      return did;
   }

   public int size(){
      return n;
   }

   public Client get(int x){
      return q[(yk + x) % QMSProps.QUEUE_SIZE];
   }

   public int space(){
      return QMSProps.QUEUE_SIZE - size();
   }

   public Client top() {
      if (size() > 0) {
         return q[yk];
      }
      return null;
   }

   public synchronized boolean put(Client c){
      if (space() > 0){
         n++;
         c.setTicketID(wk);
         c.queue = System.currentTimeMillis();
         q[wk] = c;
         wk = (wk + 1) % QMSProps.QUEUE_SIZE;
         QMSProps.clients_in_queues++;
         QMSProps.clients_waiting--;
         return true;
      }
      return false;
   }

   public synchronized Client pop(){
      if (size() > 0){
         n--;
         Client c = q[yk];
         c.serve = System.currentTimeMillis();
         q[yk] = null;
         yk = (yk + 1) % QMSProps.QUEUE_SIZE;
         QMSProps.clients_in_queues--;
         QMSProps.clients_served++;
         return c;
      }
      return null;
   }

   public String getQueueState() {
      return queueState;
   }

}
